/*
 * Copyright (C) 2016 Lokiy(liulongke@gmail.com)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  　　　　http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */

package root.electronclass.electronclass.ext

import android.content.Context
import android.os.Bundle
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentTransaction
import root.electronclass.electronclass.CommonActivity
import root.electronclass.electronclass.R

/**
 * Fragments
 * @author Lokiy
 * 2021-02-08 9:57
 */


fun Context.startFragment(clazz: Class<out Fragment>, bundle: Bundle? = null) = startFragmentForResult(clazz, bundle)

fun Context.startFragmentForResult(clazz: Class<out Fragment>, bundle: Bundle? = null, requestCode: Int = 0) =
    CommonActivity.startActivityForResult(this, clazz, bundle, requestCode)

fun Fragment.startFragment(clazz: Class<out Fragment>, bundle: Bundle? = null) = startFragmentForResult(clazz, bundle)

fun Fragment.startFragmentForResult(clazz: Class<out Fragment>, bundle: Bundle? = null, requestCode: Int = 0) =
    CommonActivity.startActivityForResult(this, clazz, bundle, requestCode)

fun Fragment.addFragment(clazz: Class<out Fragment>, bundle: Bundle? = null, tag: String? = "", transaction: FragmentTransaction.() -> Unit = {}) =
    activity?.supportFragmentManager?.also { fm ->
        val tagName = tag ?: clazz.simpleName
        var fragment: Fragment? = fm.findFragmentByTag(tagName)
        if (fragment == null) {
            fragment = clazz.newInstance().apply { arguments = bundle }
            fm.beginTransaction().also {
//                it.setCustomAnimations(R.anim.slide_in_from_right, R.anim.slide_out_to_right, R.anim.slide_in_from_right, R.anim.slide_out_to_right)
                it.transaction()
                it
                    .add(R.id.container, fragment, tagName)
                    .addToBackStack(tagName)
//            .setCustomAnimations(R.anim.push_bottom_in, R.anim.push_bottom_out)
            }.commit()
        } else if (fragment.isHidden) {
            fm.beginTransaction().show(fragment).commit()
        }
    }